package cn.team11.smarteye.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.team11.sds.dayi.R;
import cn.team11.smarteye.activity.CateyeDeviceDetailActivity;
import cn.team11.smarteye.activity.ImageDetailActivity;
import cn.team11.smarteye.activity.callback.GuestRecordCallback;
import cn.team11.smarteye.activity.callback.GuestRecordResultCallback;
import cn.team11.smarteye.adapter.CommonAdapter;
import cn.team11.smarteye.adapter.CommonViewHolder;
import cn.team11.smarteye.base.BaseDialog;
import cn.team11.smarteye.base.BaseFragment;
import cn.team11.smarteye.base.BasePresenter;
import cn.team11.smarteye.bean.RingRecordBean;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.module.MyDaoManager;
import cn.team11.smarteye.service.CatEyeService;
import cn.team11.smarteye.utils.AppLogger;
import cn.team11.smarteye.utils.ListUtils;
import cn.team11.smarteye.utils.TimeUtils;
import cn.team11.smarteye.widget.GuestCalendarPopupView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Murphy on 2017/11/1.
 */

public class GuestRecordFragment extends BaseFragment implements GuestCalendarPopupView.OnCalendarListener, GuestRecordResultCallback, CommonAdapter.OnItemClickListener{


    @BindView(R.id.guest_record_listview)
    RecyclerView mGuestRecordRV;
    @BindView(R.id.no_guest_record_img)
    ImageView mNoGuestView;
    @BindView(R.id.choose_time_bt_in_guest)
    TextView mChooseTime;
    @BindView(R.id.edit_mode_layout)
    View mEditModeLayout;

    private GuestListAdapter mAdapter;
    private GuestRecordCallback mCallback;

    private List<RingRecordBean> mRingLists = new ArrayList<>();
    private String seletedDate;
    private boolean isEditMode = false;

    private int badgeCount = 0;

    public static GuestRecordFragment newInstance(Bundle bundle) {
        GuestRecordFragment fragment = new GuestRecordFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_guest_record, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        AppLogger.i("GuestRecordFragment onViewCreated");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void setPresenter(BasePresenter presenter) {

    }

    @Override
    public void init() {
        ((CateyeDeviceDetailActivity)getActivity()).registerGuestRecordResultCallback(this);
        mCallback = (GuestRecordCallback) getActivity();
        seletedDate = TimeUtils.dateToString(new Date());

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mGuestRecordRV.setLayoutManager(linearLayoutManager);
        mAdapter = new GuestListAdapter(getActivity(), R.layout.cateye_guest_record_list_item, mRingLists);
        mGuestRecordRV.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);

        mChooseTime.setText(seletedDate.substring(5, 10));
        if (mCallback != null){
            mRingLists.clear();
            final long starttime = TimeUtils.stringToTimestamp(seletedDate.substring(0, 10) + " 00:00:00");
            mCallback.getLocalRingList(starttime, starttime+86400000)
                    .delay(6, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<RingRecordBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull RingRecordBean ringRecordBean) {
                            mRingLists.add(ringRecordBean);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            if (ListUtils.isEmpty(mRingLists)){
                                mNoGuestView.setVisibility(View.VISIBLE);
                            }else {
                                mNoGuestView.setVisibility(View.INVISIBLE);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    });

        }
    }


    @OnClick({R.id.choose_time_bt_in_guest,R.id.guest_delete_bt})
    public void onClickAction(View view){
        switch (view.getId()){
            case R.id.choose_time_bt_in_guest:
                GuestCalendarPopupView calendar = new GuestCalendarPopupView(getActivity());
                calendar.setOnCalendarListener(this);
                calendar.showAsDropDown(view, 0, 27);
                break;
            case R.id.guest_delete_bt:
                Bundle b = new Bundle();
                b.putString("title", getString(R.string.delete_guest_record));
                b.putString("content", getString(R.string.delete_guest_record_tips));
                final TextDialogFragment deleteDialog = TextDialogFragment.newInstance(b);
                deleteDialog.show(getFragmentManager(), "delete_guest_record");
                deleteDialog.setOnBtClickListener(new BaseDialog.OnBtClickListener() {
                    @Override
                    public void onConfirmClick() {
                        final List<String> fids = new ArrayList<String>();
                        Observable.fromIterable(mRingLists)
                                .filter(new Predicate<RingRecordBean>() {
                                    @Override
                                    public boolean test(@NonNull RingRecordBean ringRecordBean) throws Exception {
                                        return ringRecordBean.isSelect();
                                    }
                                })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<RingRecordBean>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {

                                    }

                                    @Override
                                    public void onNext(@NonNull RingRecordBean ringRecordBean) {
                                        mRingLists.remove(ringRecordBean);
                                        fids.add(ringRecordBean.getFid());
                                        MyDaoManager.getInstance(getActivity()).deleteRingMsgByIdAndFid(ringRecordBean.getBid(), ringRecordBean.getFid());
                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                        showGuestTips();
                                    }

                                    @Override
                                    public void onComplete() {
                                        showGuestTips();
                                        if (!ListUtils.isEmpty(fids)){
                                            mCallback.deleteRings(fids.toArray(new String[fids.size()]));
                                        }
                                        mCallback.addBadge(2, mRingLists.size());
                                        leaveEditMode();
                                    }
                                });
                        deleteDialog.dismiss();
                    }

                    @Override
                    public void onCancelClick() {
                        deleteDialog.dismiss();
                    }
                });
                break;
        }
    }


    @Override
    public void onRightButtonClick(View view) {
        if (!isEditMode){
            enterEditMode();
        } else {
            leaveEditMode();
        }

    }

    @Override
    public void onLeftButtonOnClick(View view) {
        //全选操作
        if (!((TextView)view).getText().equals("")){
            for ( int i = 0; i < mRingLists.size(); i++){
                mRingLists.get(i).setSelect(true);
            }
            mAdapter.notifyDataSetChanged();
        } else {
            getActivity().finish();
        }
    }

    @Override
    public void onSelectedDateString(String dateStr) {
        mRingLists.clear();
        seletedDate = dateStr;
        mChooseTime.setText(dateStr.substring(5, 10));
        if (mCallback != null){
            mRingLists.clear();
            final long starttime = TimeUtils.stringToTimestamp(seletedDate.substring(0, 10) + " 00:00:00");
            mCallback.getLocalRingList(starttime, starttime+86400000)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<RingRecordBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull RingRecordBean ringRecordBean) {
                            mRingLists.add(ringRecordBean);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            showGuestTips();
                            mAdapter.notifyDataSetChanged();
                        }
                    });

        }
    }

    @Override
    public void onItemClick(View view, int position) {
        if (isEditMode){
            CommonViewHolder holder = (CommonViewHolder) mGuestRecordRV.getChildViewHolder(view);
            boolean isSel = mRingLists.get(position).isSelect();
            if (isSel){
                mRingLists.get(position).setSelect(false);
            } else {
                mRingLists.get(position).setSelect(true); }
            if (mRingLists.get(position).isSelect()){//如果被选中
                holder.getView(R.id.guest_check_status_bt).setSelected(true);
                holder.getConvertView().setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_item_selected));
            } else {
                holder.getView(R.id.guest_check_status_bt).setSelected(false);
                holder.getConvertView().setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_white));
            }
        } else {
            String bid = mRingLists.get(position).getBid();
            String fid = mRingLists.get(position).getFid();
            Intent intent = new Intent(getActivity(), ImageDetailActivity.class);
            intent.putExtra(SConstants.BID, bid);
            intent.putExtra(SConstants.FIDS, fid);
            intent.putExtra(SConstants.IMAGE_TYPE, SConstants.GUEST_IMAGE);
            intent.putExtra(SConstants.CREATE_TIME, mRingLists.get(position).getRingtime());
            getActivity().startActivity(intent);
        }
    }

    /**
     * 进入编辑状态
     * */
    private void enterEditMode(){
        if (mCallback != null){
            isEditMode = true;
            mCallback.setCanScroll(false);
            mEditModeLayout.setVisibility(View.VISIBLE);
            mCallback.setCustomTitle(getResources().getString(R.string.cancel), 1);
            mCallback.setCustomTitle(getResources().getString(R.string.select_all), -1);
            mCallback.setCustomTitleImage(null, -1);
            mCallback.setTabVisiable(View.GONE);
            mAdapter.setEditMode(isEditMode);
        }
    }

    /**
     * 离开编辑状态
     * */
    private void leaveEditMode(){
        if (mCallback != null){
            isEditMode = false;
            mCallback.setCanScroll(true);
            mEditModeLayout.setVisibility(View.INVISIBLE);
            mCallback.setCustomTitle(getResources().getString(R.string.edit_txt), 1);
            mCallback.setCustomTitle("", -1);
            Drawable iconDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.nav_icon_back);
            iconDrawable.setBounds(0, 0, UIUtil.dip2px(getActivity(), 20), UIUtil.dip2px(getActivity(), 20));
            mCallback.setCustomTitleImage(iconDrawable, -1);
            mCallback.setTabVisiable(View.VISIBLE);
            mAdapter.setEditMode(isEditMode);
        }
    }

    @Override
    public void onNewGuestRecordReceived(RingRecordBean record) {
        if (record != null) {
            mRingLists.add(record);
            badgeCount++;
            showGuestTips();
            mAdapter.notifyDataSetChanged();
            if (mCallback != null){
                mCallback.addBadge(2, badgeCount);
            }
        }
    }

    private void showGuestTips(){
        if (ListUtils.isEmpty(mRingLists)){
            mNoGuestView.setVisibility(View.VISIBLE);
        }else {
            mNoGuestView.setVisibility(View.INVISIBLE);
        }
    }
    @Override
    public void resetBadgeCount() {
        badgeCount = 0;
    }

    /**
     * Created by Yang on 2017/11/18.
     */

    public class GuestListAdapter extends CommonAdapter<RingRecordBean> {

        private boolean isEditable = false;

        public GuestListAdapter(Context mContext, int mLayoutId, List<RingRecordBean> mDatas) {
            super(mContext, mLayoutId, mDatas);
        }

        @Override
        public void convert(CommonViewHolder holder, RingRecordBean ringRecordBean) {
            holder.setText(R.id.guest_record_time, TimeUtils.timeMinute(ringRecordBean.getRingtime()));
            holder.setText(R.id.guest_record_txt, mCallback.getNickName());
            ImageView thumbView = holder.getView(R.id.guest_record_thumb);
            ImageView checkable = holder.getView(R.id.guest_check_status_bt);
            if (isEditable){
                checkable.setVisibility(View.VISIBLE);
                if (ringRecordBean.isSelect()){
                    checkable.setSelected(true);
                    holder.getConvertView().setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_item_selected));
                }
            } else {
                checkable.setVisibility(View.INVISIBLE);
                holder.getConvertView().setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_white));
                ringRecordBean.setSelect(false);
                checkable.setSelected(false);
            }
            //加载一张缩略图
            if (CatEyeService.icvss != null){
                String imgUrl = CatEyeService.icvss.equesGetRingPictureUrl(ringRecordBean.getFid(), ringRecordBean.getBid()).toString();
                Glide.with(mContext).load(imgUrl).override(UIUtil.dip2px(mContext, 120), UIUtil.dip2px(mContext, 100)).into(thumbView);
            }
        }

        public void setEditMode(boolean isEdit){
            this.isEditable = isEdit;
            notifyDataSetChanged();
        }
    }
}
